"use client"

import { useEffect, useRef } from "react"
import {
  deserializeHighlightRange,
  applyHighlightToRange,
} from "@/lib/highlight-positioning"

interface SharedHighlightData {
  highlightedText: string
  textOffset: number
  textLength: number
  textPrefix: string
  textSuffix: string
}

interface SharedEntryContentProperties {
  sanitisedHtml: string
  highlightData: SharedHighlightData | null
}

export function SharedEntryContent({
  sanitisedHtml,
  highlightData,
}: SharedEntryContentProperties) {
  const containerReference = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const container = containerReference.current
    if (!container) return

    container.innerHTML = sanitisedHtml

    if (!highlightData) return

    const highlightRange = deserializeHighlightRange(container, highlightData)
    if (!highlightRange) return

    applyHighlightToRange(highlightRange, "shared-highlight", "yellow", false)

    requestAnimationFrame(() => {
      const markElement = container.querySelector(
        'mark[data-highlight-identifier="shared-highlight"]'
      )
      if (markElement) {
        markElement.scrollIntoView({ behavior: "smooth", block: "center" })
      }
    })
  }, [sanitisedHtml, highlightData])

  return (
    <div
      ref={containerReference}
      className="prose-reader text-text-secondary"
    />
  )
}
